<template>
    <div class="slaughter-info">
        <!-- 屠宰信息 -->
        <div class="info-section">
            <div class="section-header">
                <h3>屠宰信息</h3>
                <el-button @click="openSlaughterEdit">设置</el-button>
            </div>
            <div class="info-display">
                <div class="info-column">
                    <div class="info-item">批次号：{{ localSlaughterInfo.batch_No }}</div>
                    <div class="info-item">平均重量：{{ localSlaughterInfo.average_Weight }} kg</div>
                    <div class="info-item">到达时间：{{ localSlaughterInfo.arrival_Time }}</div>
                </div>
                <div class="info-column">
                    <div class="info-item">屠宰时间：{{ localSlaughterInfo.slaughter_Time }}</div>
                </div>
            </div>
        </div>



        <!-- 屠宰证书 -->
        <div class="certificate-section">
            <div class="section-header">
                <h3>屠宰证书</h3>
            </div>
            <div class="upload-area">
                <MultiImageUpload :model-value="localCertificateImgs" :max-count="5" :upload-text="'上传屠宰证书'"
                    :traceability-id="props.traceabilityId" field-type="Food_Safety"
                    @update:model-value="updateCertificateImgs" @upload-success="onCertificateUploadSuccess"
                    @remove="onCertificateRemove" />
            </div>
        </div>

        <!-- 企业信息 -->
        <div class="enterprise-section">
            <div class="section-header">
                <h3>企业信息</h3>
                <el-button @click="openEnterpriseEdit">设置</el-button>
            </div>
            <div class="info-display">
                <div class="info-item">企业名称：{{ enterpriseInfo.corporate_Name || '四川锦祥屠宰场' }}</div>
                <div class="info-item">省份：{{ enterpriseInfo.province || '四川省' }}</div>
                <div class="info-item">城市：{{ enterpriseInfo.ocation_City || '成都市' }}</div>
                <div class="info-item">详细地址：{{ enterpriseInfo.detailed_Addres || '锦江区XX路XX号' }}</div>
                <div class="info-item">成立日期：{{ enterpriseInfo.establishment_Date || '2020-01-01' }}</div>
                <div class="info-item">企业简介：{{ enterpriseInfo.company_Profile || '专业从事屠宰加工的企业' }}</div>
            </div>
        </div>

        <!-- 企业照片 -->
        <div class="photos-section">
            <div class="section-header">
                <h3>企业照片</h3>
            </div>
            <div class="upload-area">
                <MultiImageUpload :model-value="localEnterprisePhotoImgs" :max-count="5" :upload-text="'上传企业照片'"
                    :traceability-id="props.traceabilityId" field-type="Certification_Documents"
                    @update:model-value="updateEnterprisePhotoImgs" @upload-success="onEnterprisePhotoUploadSuccess"
                    @remove="onEnterprisePhotoRemove" />
            </div>
        </div>

        <!-- 屠宰信息编辑弹窗 -->
        <el-dialog v-model="slaughterEditVisible" title="屠宰信息" width="500px">
            <el-form :model="slaughterForm" label-width="100px">
                <el-form-item label="批次号：">
                    <el-input v-model="slaughterForm.batch_No" placeholder="请输入批次号" />
                </el-form-item>
                <el-form-item label="平均重量：">
                    <el-input v-model="slaughterForm.average_Weight" placeholder="请输入平均重量(kg)" />
                </el-form-item>
                <el-form-item label="到达时间：">
                    <el-date-picker v-model="slaughterForm.arrival_Time" type="datetime" placeholder="请选择到达时间" />
                </el-form-item>
                <el-form-item label="屠宰时间：">
                    <el-date-picker v-model="slaughterForm.slaughter_Time" type="datetime" placeholder="请选择屠宰时间" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="slaughterEditVisible = false">取消</el-button>
                <el-button type="primary" @click="saveSlaughterInfo">保存</el-button>
            </template>
        </el-dialog>

        <!-- 企业信息编辑弹窗 -->
        <el-dialog v-model="enterpriseEditVisible" title="企业信息" width="500px">
            <el-form :model="enterpriseForm" label-width="120px">
                <el-form-item label="企业名称：">
                    <el-input v-model="enterpriseForm.corporate_Name" placeholder="请输入企业名称" />
                </el-form-item>
                <el-form-item label="省份：">
                    <el-input v-model="enterpriseForm.province" placeholder="请输入省份" />
                </el-form-item>
                <el-form-item label="城市：">
                    <el-input v-model="enterpriseForm.ocation_City" placeholder="请输入城市" />
                </el-form-item>
                <el-form-item label="详细地址：">
                    <el-input v-model="enterpriseForm.detailed_Addres" placeholder="请输入详细地址" />
                </el-form-item>
                <el-form-item label="成立日期：">
                    <el-date-picker v-model="enterpriseForm.establishment_Date" type="date" placeholder="请选择成立日期" />
                </el-form-item>
                <el-form-item label="企业简介：">
                    <el-input v-model="enterpriseForm.company_Profile" type="textarea" placeholder="请输入企业简介" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="enterpriseEditVisible = false">取消</el-button>
                <el-button type="primary" @click="saveEnterpriseInfo">保存</el-button>
            </template>
        </el-dialog>


    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Write, Read } from '@/components/Http/axiosHepler';
import MultiImageUpload from '@/components/MultiImageUpload.vue';
import { useCounterStore } from "@/stores/counter"
import { useRoute, useRouter } from 'vue-router';

const Router = useRouter();
const Route = useRoute();
const store = useCounterStore();

// 定义props
const props = withDefaults(defineProps<{
    traceabilityId?: number;
    slaughterInfo?: any;
    enterpriseInfo?: any;
    certificateImgs?: string[];
    enterprisePhotoImgs?: string[];
}>(), {
    traceabilityId: 0,
    slaughterInfo: () => ({}),
    enterpriseInfo: () => ({}),
    certificateImgs: () => [],
    enterprisePhotoImgs: () => []
});

// 定义emits
const emit = defineEmits<{
    'update:slaughterInfo': [value: any];
    'update:enterpriseInfo': [value: any];
    'update:certificateImgs': [value: string[]];
    'update:enterprisePhotoImgs': [value: string[]];
    'certificate-remove': [index: number, image: any];
    'enterprise-photo-remove': [index: number, image: any];
}>();

const slaughterEditVisible = ref(false);
const enterpriseEditVisible = ref(false);


// 本地图片数组
const localCertificateImgs = ref<string[]>([]);
const localEnterprisePhotoImgs = ref<string[]>([]);

// 本地屠宰信息数据
const localSlaughterInfo = ref({
    "slaughterId": "",
    "batch_No": "",
    "average_Weight": "",
    "arrival_Time": "",
    "slaughter_Time": "",
    "traceabilityId": "",
});



// 监听props变化
watch(() => props.certificateImgs, (newVal) => {
    localCertificateImgs.value = newVal ? [...newVal] : [];
}, { immediate: true });

watch(() => props.enterprisePhotoImgs, (newVal) => {
    localEnterprisePhotoImgs.value = newVal ? [...newVal] : [];
}, { immediate: true });

// 获取屠宰信息
const getSlaughterInfo = () => {
    if (!props.traceabilityId || props.traceabilityId === 0) {
        console.warn('traceabilityId为空，无法获取屠宰信息');
        return;
    }

    Read.get('/Management/SlaughterShow', {
        params: {
            TraceabilityId: props.traceabilityId
        }
    }).then(res => {
        console.log('屠宰信息接口返回:', res.data);
        if (res.data.code === 200 && res.data.data) {
            const data = res.data.data;
            const slaughterData = Array.isArray(data) ? data[0] : data;

            if (slaughterData) {
                Object.assign(localSlaughterInfo.value, {
                    slaughterId: slaughterData.slaughterId || '',
                    batch_No: slaughterData.batch_No || '',
                    average_Weight: slaughterData.average_Weight || '',
                    arrival_Time: slaughterData.arrival_Time || '',
                    slaughter_Time: slaughterData.slaughter_Time || '',
                    traceabilityId: slaughterData.traceabilityId || props.traceabilityId
                });
                emit('update:slaughterInfo', localSlaughterInfo.value);
            }
        }
    }).catch(err => {
        console.error('获取屠宰信息失败:', err);
        ElMessage.error('获取屠宰信息失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
    });
};

// 获取企业信息
const getEnterpriseInfo = () => {
    if (!props.traceabilityId || props.traceabilityId === 0) {
        console.warn('traceabilityId为空，无法获取企业信息');
        return;
    }

    Read.get('/Breeding/CompanyShow', {
        params: {
            TraceabilityId: props.traceabilityId
        }
    }).then(res => {
        console.log('企业信息接口返回:', res.data);
        if (res.data.code === 200 && res.data.data) {
            const data = res.data.data;
            const enterpriseData = Array.isArray(data) ? data[0] : data;

            if (enterpriseData) {
                const updatedInfo = {
                    corporate_Name: enterpriseData.corporate_Name || '',
                    province: enterpriseData.province || '',
                    ocation_City: enterpriseData.ocation_City || '',
                    detailed_Addres: enterpriseData.detailed_Addres || '',
                    establishment_Date: enterpriseData.establishment_Date || '',
                    company_Profile: enterpriseData.company_Profile || ''
                };
                emit('update:enterpriseInfo', updatedInfo);
            }
        }
    }).catch(err => {
        console.error('获取企业信息失败:', err);
        ElMessage.error('获取企业信息失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
    });
};



// 更新图片数组
const updateCertificateImgs = (newImgs: string[]) => {
    localCertificateImgs.value = newImgs;
    emit('update:certificateImgs', newImgs);
};

const updateEnterprisePhotoImgs = (newImgs: string[]) => {
    localEnterprisePhotoImgs.value = newImgs;
    emit('update:enterprisePhotoImgs', newImgs);
};

// 表单数据
const slaughterForm = reactive({
    "slaughterId": "",
    "batch_No": "",
    "average_Weight": "",
    "arrival_Time": "",
    "slaughter_Time": "",
    "traceabilityId": "",
});

const enterpriseForm = reactive({
    corporate_Name: '',
    province: '',
    ocation_City: '',
    detailed_Addres: '',
    establishment_Date: '',
    company_Profile: ''
});

// 打开屠宰信息编辑
const openSlaughterEdit = () => {
    Object.assign(slaughterForm, localSlaughterInfo.value);
    slaughterEditVisible.value = true;
};

// 保存屠宰信息
const saveSlaughterInfo = () => {
    if (!props.traceabilityId || props.traceabilityId === 0) {
        ElMessage.error('溯源ID不能为空');
        return;
    }

    const missingFields = [];

    if (!slaughterForm.batch_No) missingFields.push('批次号');
    if (!slaughterForm.average_Weight) missingFields.push('平均重量');
    if (!slaughterForm.arrival_Time) missingFields.push('到达时间');
    if (!slaughterForm.slaughter_Time) missingFields.push('屠宰时间');

    if (missingFields.length > 0) {
        ElMessage.error(`请填写以下必填字段：${missingFields.join('、')}`);
        return;
    }

    const payload = {
        traceabilityId: props.traceabilityId,
        batch_No: slaughterForm.batch_No,
        average_Weight: Number(slaughterForm.average_Weight),
        arrival_Time: slaughterForm.arrival_Time,
        slaughter_Time: slaughterForm.slaughter_Time
    };

    Write.post('/Management/SlaughterCreate', payload).then(res => {
        if (res.data.code == 200) {
            Object.assign(localSlaughterInfo.value, {
                slaughterId: res.data.data?.slaughterId || '',
                batch_No: slaughterForm.batch_No,
                average_Weight: slaughterForm.average_Weight,
                arrival_Time: slaughterForm.arrival_Time,
                slaughter_Time: slaughterForm.slaughter_Time,
                traceabilityId: props.traceabilityId
            });
            emit('update:slaughterInfo', localSlaughterInfo.value);
            slaughterEditVisible.value = false;
            ElMessage.success('保存成功');
            getSlaughterInfo();
        } else {
            ElMessage.error(res.data.message || '保存失败');
        }
    }).catch(err => {
        console.error('保存屠宰信息失败:', err);
        ElMessage.error('保存失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
    });
};

// 打开企业信息编辑
const openEnterpriseEdit = () => {
    Object.assign(enterpriseForm, props.enterpriseInfo);
    enterpriseEditVisible.value = true;
};

// 保存企业信息
const saveEnterpriseInfo = () => {
    if (!props.traceabilityId || props.traceabilityId === 0) {
        ElMessage.error('溯源ID不能为空');
        return;
    }

    const missingFields = [];

    if (!enterpriseForm.corporate_Name) missingFields.push('企业名称');
    if (!enterpriseForm.province) missingFields.push('省份');
    if (!enterpriseForm.ocation_City) missingFields.push('城市');
    if (!enterpriseForm.detailed_Addres) missingFields.push('详细地址');
    if (!enterpriseForm.establishment_Date) missingFields.push('成立日期');
    if (!enterpriseForm.company_Profile) missingFields.push('企业简介');

    if (missingFields.length > 0) {
        ElMessage.error(`请填写以下必填字段：${missingFields.join('、')}`);
        return;
    }

    const payload = {
        traceabilityId: props.traceabilityId,
        corporate_Name: enterpriseForm.corporate_Name,
        province: enterpriseForm.province,
        ocation_City: enterpriseForm.ocation_City,
        detailed_Addres: enterpriseForm.detailed_Addres,
        establishment_Date: enterpriseForm.establishment_Date,
        company_Profile: enterpriseForm.company_Profile
    };

    Write.post('/Management/CompanyCreates', payload).then(res => {
        if (res.data.code == 200) {
            const updatedInfo = {
                corporate_Name: enterpriseForm.corporate_Name,
                province: enterpriseForm.province,
                ocation_City: enterpriseForm.ocation_City,
                detailed_Addres: enterpriseForm.detailed_Addres,
                establishment_Date: enterpriseForm.establishment_Date,
                company_Profile: enterpriseForm.company_Profile
            };
            emit('update:enterpriseInfo', updatedInfo);
            enterpriseEditVisible.value = false;
            ElMessage.success('保存成功');
            getEnterpriseInfo();
        } else {
            ElMessage.error(res.data.message || '保存失败');
        }
    }).catch(err => {
        console.error('保存企业信息失败:', err);
        ElMessage.error('保存失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
    });
};



// 图片上传事件处理
const onCertificateUploadSuccess = async (image: any) => {
    console.log('屠宰证书上传成功:', image);

    // 检查traceabilityId是否存在
    if (!props.traceabilityId || props.traceabilityId === 0) {
        ElMessage.error('溯源ID不能为空，请先保存基本信息');
        return;
    }

    // 图片已经通过 uploadHelper.ts 保存到数据库
    // MultiImageUpload组件会自动管理图片列表，这里不需要额外处理
    if (image && image.url) {
        console.log('屠宰证书图片URL:', image.url);
        ElMessage.success('屠宰证书上传完成');
    }
};

const onCertificateRemove = async (index: number, image: any) => {
    console.log('屠宰证书删除事件触发:', index, image);

    // 删除操作已经在 MultiImageUpload 组件中处理
    // 这里只需要触发父组件的删除事件，让父组件知道有删除操作
    emit('certificate-remove', index, image);

    // 延迟一下再显示消息，避免与MultiImageUpload的消息冲突
    setTimeout(() => {
        ElMessage.success('屠宰证书删除完成');
    }, 100);
};

const onEnterprisePhotoUploadSuccess = async (image: any) => {
    console.log('企业照片上传成功:', image);

    // 检查traceabilityId是否存在
    if (!props.traceabilityId || props.traceabilityId === 0) {
        ElMessage.error('溯源ID不能为空，请先保存基本信息');
        return;
    }

    // 图片已经通过 uploadHelper.ts 保存到数据库
    // MultiImageUpload组件会自动管理图片列表，这里不需要额外处理
    if (image && image.url) {
        console.log('企业照片URL:', image.url);
        ElMessage.success('企业照片上传完成');
    }
};

const onEnterprisePhotoRemove = async (index: number, image: any) => {
    console.log('企业照片删除事件触发:', index, image);

    // 删除操作已经在 MultiImageUpload 组件中处理
    // 这里只需要触发父组件的删除事件，让父组件知道有删除操作
    emit('enterprise-photo-remove', index, image);

    // 延迟一下再显示消息，避免与MultiImageUpload的消息冲突
    setTimeout(() => {
        ElMessage.success('企业照片删除完成');
    }, 100);
};

// 组件挂载时获取数据
onMounted(() => {
    console.log('SlaughterInfo组件挂载，traceabilityId:', props.traceabilityId);

    if (props.traceabilityId) {
        getSlaughterInfo();
        getEnterpriseInfo(); // 组件挂载时获取企业信息
    } else {
        console.warn('traceabilityId为空，无法获取屠宰信息');
    }
});

// 监听traceabilityId变化
watch(() => props.traceabilityId, (newVal) => {
    if (newVal) {
        console.log('traceabilityId变化，重新获取数据:', newVal);
        getSlaughterInfo();
        getEnterpriseInfo();
    }
});
</script>

<style scoped>
.slaughter-info {
    padding: 24px;
}

.info-section,
.quarantine-section,
.certificate-section,
.enterprise-section,
.photos-section {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #e4e7ed;
}

.section-header h3 {
    margin: 0;
    color: #303133;
    font-size: 16px;
    font-weight: 600;
}

.info-display {
    display: flex;
    gap: 40px;
}

.info-column {
    flex: 1;
}

.info-item {
    margin-bottom: 12px;
    color: #606266;
    font-size: 14px;
    line-height: 1.5;
}



.upload-area {
    padding: 16px 0;
}

.certificate-section,
.photos-section {
    background: #f8f9fa;
}

.enterprise-section .info-display {
    display: block;
}

.enterprise-section .info-item {
    margin-bottom: 8px;
}
</style>